package com.rpc.learn.regist;

import com.rpc.learn.transport.NettyRpcServer;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * TODO 实际上应该是单例
 */
public class LocalFileServiceRegister implements ServiceRegister{
    private static final String PATH = "register/dir";
    private static final File dir = new File(PATH);

    @Override
    public void regist(String serviceName) {
        if(!dir.exists()) {
            dir.mkdirs();
        }
        File service = new File(PATH + "/" + serviceName);
        service.deleteOnExit();
        try {
            service.createNewFile();
            FileWriter fw = new FileWriter(service);
            fw.write(InetAddress.getLocalHost().getHostAddress() + "@@" + NettyRpcServer.PORT);
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public InetSocketAddress lookup(String serviceName) {
        File service = new File(PATH + "/" + serviceName);
        if(!service.exists()) {
            return null;
        }
        try {
            BufferedReader br = new BufferedReader(new FileReader(service));
            String ipPort = br.readLine();
            String[] split = ipPort.split("@@");
            return new InetSocketAddress(split[0], Integer.parseInt(split[1]));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
